package com.hmdp.core.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.dto.LoginFormDTO;
import com.hmdp.entity.dto.Result;
import com.hmdp.entity.db.User;
import com.hmdp.core.mapper.UserMapper;
import com.hmdp.core.service.IUserService;
import com.hmdp.entity.dto.UserDTO;
import com.hmdp.common.constant.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.common.constant.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisServiceImpl redisService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.不符合返回错误信息
            return Result.fail("手机号格式错误");
        }

        //3.符合，生成验证码
//        String code = RandomUtil.randomNumbers(6);
        String code = phone.substring(0,6);

        //4.保存验证码
        redisService.set(RedisConstants.LOGIN_CODE_KEY + phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //5.发送验证码
        log.info("验证码为：{}",code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.不符合返回错误信息
            return Result.fail("手机号格式错误");
        }

        //2.校验验证码
        String cacheCode = redisService.get(RedisConstants.LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if(StringUtils.isBlank(cacheCode) || !code.equals(cacheCode)){
            return Result.fail("验证码错误");
        }

        //3.根据手机号查询用户
        User user = lambdaQuery().eq(User::getPhone, phone).one();

        //4.判断用户是否存在，否则创建用户
        if(Objects.isNull(user)){
            user = newUserWithPhone(phone);
        }

        //5.保存用户信息到session
        //5.1生成token
        String token = UUID.randomUUID().toString(true);
        //5.2保存数据到Redis
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        userDTO.setToken(token);
        redisService.putAll(RedisConstants.LOGIN_USER_KEY + token,userDTO,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);

        //6.返回token
        return Result.ok(token);
    }

    @Override
    public Result logOut() {
        String token = UserHolder.getUser().getToken();
        String key = RedisConstants.LOGIN_USER_KEY + token;
        redisService.delete(key);
        return Result.ok();
    }

    private User newUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(10));
        save(user);
        return user;
    }

    @Override
    public Result sign() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String nowStr = LocalDateTimeUtil.format(now, "yyyyMM");
        String key = RedisConstants.USER_SIGN_KEY + userId + ":" + nowStr;

        int dayOfMonth = now.getDayOfMonth();
        //写入redis SETBIT ket offset 1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        // 1. 获取本月截止目前的所有签到记录
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String nowStr = LocalDateTimeUtil.format(now, "yyyyMM");
        String key = RedisConstants.USER_SIGN_KEY + userId + ":" + nowStr;
        int dayOfMonth = now.getDayOfMonth();
        log.info("dayOfMonth:{}",dayOfMonth);
        // BITFIELD key GET u[dayOfMonth] 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
                );
        if(result == null || result.isEmpty()) {
            return Result.ok(0);
        }
        Long num = result.get(0);
        if(num == null || num == 0) {
            return Result.ok(0);
        }

        // 2. 循环遍历，统计最长连续签到数
        int count = 0;
        while (true) {
            // 2.1 与1做与运算，得到最后一个bit位
            if((num & 1) == 0) {
                break;
            } else {
                count ++;
            }
            // 右移
            num >>>= 1;
        }
        return Result.ok(count);
    }
}
